use axum::{routing, Router};
use tokio::net::TcpListener;
use crate::{redis, router};
use crate::filter::auth;

/// 启动axum的web服务
pub(crate) async fn start() -> anyhow::Result<()> {
    let sse_router = router::see_router();
    let user_router = router::user_router();

    let mut router = Router::new()
        .route("/", routing::get(async || "Hello rust axum"))
        .route("/keys", routing::get(async || {
            redis::keys("*").await.unwrap();
        }));

    router = router.merge(sse_router?);
    router = router.merge(user_router?);
    
    router = router.layer(axum::middleware::from_fn(auth::auth_filter));

    let server_config = crate::config::get().server()?;

    tracing::info!("配置http监听url: http://{}:{}", server_config.host(), server_config.port());
    let listener = TcpListener::bind(format!("{}:{}", server_config.host(), server_config.port())).await?;

    axum::serve(listener, router).await?;

    Ok(())
}